package com.future.cb.web.interceptor;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.future.cb.common.annotation.NoNeedLoginIn;
import com.future.cb.common.exception.AuthenException;
import com.future.cb.common.utils.TokenUtil;
import com.future.cb.dao.entity.SysUser;
import com.future.cb.service.SysUserService;
import com.future.cb.web.global.PlatFormContext;

import net.minidev.json.JSONObject;
public class AuthenInterceptor implements HandlerInterceptor {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private TokenUtil tokenUtil;

	/**
	 * 采用jwt验证
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			NoNeedLoginIn noNeedLoginIn = method.getMethodAnnotation(NoNeedLoginIn.class);
			// 需要登录
			if (noNeedLoginIn == null || !noNeedLoginIn.value()) {
				String token = request.getHeader("Authorization");
				if(StringUtils.isEmpty(token)){
					throw new AuthenException("认证信息为空!");
				}
				JSONObject result = this.tokenUtil.parseToken(token);
				String userid = result.getAsString("userid");
				SysUser currentUser = this.sysUserService.findUserById(userid);
				if(currentUser == null){
					throw new AuthenException("用户信息不存在!");
				}
				PlatFormContext.setCurrentUser(currentUser);
			}

		}
		return true;

	}
}
